package cn.liyunqi.prplug.controller;

import cn.liyunqi.prplug.util.PrPlugUtil;
import cn.liyunqi.prplug.view.AlertUtil;
import javafx.fxml.FXML;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

import java.io.*;
import java.net.URL;
import java.util.ResourceBundle;

public class SNMessageController extends BaseFXController{

    private static final String path = "." + File.separator + PrPlugController.APPDATA_FOLDER + File.separator + PrPlugController.APPDATA_SN;

    private PrPlugController prPlugController;

    public PrPlugController getPrPlugController() {
        return prPlugController;
    }

    public void setPrPlugController(PrPlugController prPlugController) {
        this.prPlugController = prPlugController;
    }

    @FXML
    private WebView webView;

    @FXML
    private TextField sn;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        WebEngine webEngine = webView.getEngine();

//        webEngine.getLoadWorker().stateProperty()
//                .addListener(new ChangeListener<State>() {
//                    @Override
//                    public void changed(ObservableValue ov, State oldState, State newState) {
//
//                        if (newState == Worker.State.SUCCEEDED) {
//                            stage.setTitle(webEngine.getLocation());
//                        }
//
//                    }
//                });
        webEngine.load("http://app-auth.liyunqi.cn/app-auth/pr-plug/index.html");


        String snValue = getSN();
        if(snValue != null){
            sn.setText(snValue);
        }

    }

    public static String getSN(){
        return PrPlugUtil.getValueFromFile(path);
    }

    @FXML
    public void saveSN(){
        String snValue = sn.getText();

        if(PrPlugUtil.isEmpty(snValue)){
            AlertUtil.showErrorAlert("请输入序列号");
            return;
        }

        int result = PrPlugUtil.authApp(snValue);

        if(result == 0){
            File file = new File(path);

            try {
                Writer out = new FileWriter(file);
                out.write(snValue);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            AlertUtil.showInfoAlert("序列号验证成功");

            getDialogStage().close();
        }
    }
}
